#include <iostream>
#include<cstdio>
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;

int main()
{
    // 创建sockfd
    int sfd=socket(AF_INET,SOCK_STREAM,0);
    if(sfd==-1)
    {
        perror("socket");
        exit(-1);
    }

    //初始化
    sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(8080);
    server_addr.sin_addr.s_addr=INADDR_ANY;

    // bind
    int n=bind(sfd,(sockaddr*)&server_addr,sizeof(server_addr));
    if(n==-1)
    {
        perror("bind");
        exit(-1);
    }

    //listen
    n=listen(sfd,SOMAXCONN);
    if(n==-1)
    {
        perror("listen");
        exit(-1);
    }

    //accept
    sockaddr_in client_addr;
    socklen_t len=sizeof(client_addr);
    
    int cfd=accept(sfd,(sockaddr*)&client_addr,&len);
    if(cfd==-1)
    {
        perror("accept");
        exit(-1);
    }


    while(true)
    {
        char buffer[1024]={0};
        int n=recv(cfd,buffer,sizeof(buffer)-1,0);
        
        if(n>0)
        {
            buffer[n]=0;
            cout<<"client say: "<<buffer<<endl; 
            send(cfd, buffer, sizeof(buffer), 0);  
        }
        else if(n==0)
        {
            cout<<"client disconnect..."<<endl;
            break;
        }
        else
        {
            perror("recv");
            break;
        }
    }

    close(sfd);
    close(cfd);
    return 0;
}
    
